package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.dto.AttrEntityDto;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrEntityVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Attr;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private AttrDao attrDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryServiceImpl categoryService;
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存属性【规格参数，销售属性】
     *
     * @param attr
     */
    @Override
    public void saveAttr(AttrEntityVo attr) {
        //保存自己的属性
        this.save(attr);
        //保存属性-属性分组的关联。
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_ENUM_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attr, attrAttrgroupRelationEntity);
            relationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 获取分类规格参数
     *
     * @param params
     * @param attrType
     * @return
     */
    @Override
    public PageUtils baseQueryList(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_ENUM_BASE.getCode() : ProductConstant.AttrEnum.ATTR_ENUM_SALE.getCode());
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            //添加检索条件
            wrapper.and(obj ->
                    obj.eq("att_id", key).or().like("attr_name", key)
            );
        }

        //分页
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        //遍历数据
        List<AttrEntityDto> attrEntityDtoList = page.getRecords().stream()
                .map(attrEntity -> {
                    //拷贝
                    AttrEntityDto attrEntityDto = new AttrEntityDto();
                    BeanUtils.copyProperties(attrEntity, attrEntityDto);
                    //赋值
                    //分组名称
                    //找到该属性下分组的id
                    //先在关联表找到分组id
                    if ("base".equalsIgnoreCase(attrType)) {
                        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntityDto.getAttrId()));
                        //然后根据分组id在分组表里找到分组名字
                        if (relationEntity != null) {
                            AttrGroupEntity byId = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                            //赋分组名称
                            if (!StringUtils.isEmpty(byId.getAttrGroupName()))
                            attrEntityDto.setGroupName(byId.getAttrGroupName());
                        }
                    }
                    //商品分类名称
                    CategoryEntity categoryEntity = categoryDao.selectById(attrEntityDto.getCatelogId());
                    if (categoryEntity != null) {
                        attrEntityDto.setCatelogName(categoryEntity.getName());
                    }
                    return attrEntityDto;
                })
                .collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrEntityDtoList);

        return pageUtils;
    }

    /**
     * 查询属性详情
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrEntityDto getDetailById(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrEntityDto attrEntityDto = new AttrEntityDto();
        BeanUtils.copyProperties(byId, attrEntityDto);
        //赋分组id
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
            attrEntityDto.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            attrEntityDto.setGroupName(attrGroupEntity.getAttrGroupName());
        }
        //赋分类完整路径
        List<Long> longList = new ArrayList<>();
        longList = categoryService.findCategoryPath(attrEntityDto.getCatelogId(), longList);
        attrEntityDto.setCatelogPath(longList);
        return attrEntityDto;
    }

    /**
     * 修改属性
     *
     * @param attrEntityVo
     */
    @Override
    public void updateAttr(AttrEntityVo attrEntityVo) {
        //修改基本数据
        this.updateById(attrEntityVo);
        //修改关联
        //修改分组和属性的联系
        if (attrEntityVo.getAttrType() == ProductConstant.AttrEnum.ATTR_ENUM_BASE.getCode()) {
            //        attrAttrgroupRelationDao.updateRelati on(attrEntityVo.getAttrId(),attrEntityVo.getAttrGroupId());
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntityVo.getAttrId());
            relationEntity.setAttrGroupId(attrEntityVo.getAttrGroupId());
            Integer count = attrAttrgroupRelationDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntityVo.getAttrId()));
            //判断这个属性有没有分组  ，如果没有分组，就添加，如果有分组， 就修改
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntityVo.getAttrId()));
            } else {
                //新增关联
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    /**
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils queryNoAttrs(Long attrgroupId, Map<String, Object> params) {
        //先找到当前分组的分类id
        Long catelogId = attrGroupDao.selectById(attrgroupId).getCatelogId();
        //先找到当前分类下的分组
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> attrGroupIds = attrGroupEntityList.stream()
                .map(attrGroupEntity -> {
                    return attrGroupEntity.getAttrGroupId();
                })
                .collect(Collectors.toList());
        //然后根据这些分组id找到所有属性id
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
        List<Long> attrIds = relationEntities.stream()
                .map(relationEntity -> {
                    return relationEntity.getAttrId();
                })
                .collect(Collectors.toList());
        //然后在排除当前分类的属性下的这些属性id
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId);
        //如果分组下有属性关联才拼接，不然就直接查这个分类的所有属性呢
        if (!CollectionUtils.isEmpty(attrIds)) {
            queryWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> {
                w.like("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }
}